package yxy.game.pm2.command.union.leader;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionLeaderMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;

/** 联盟盟主 联盟申请全部拒绝 */
@MessageType(proto = Command.UnionApplyAllRefuse, classtype = UnionLeaderMessage.UnionApplyAllRefuseRequest.class)
public class CMD_UnionApplyAllRefuse extends Command<UnionLeaderMessage.UnionApplyAllRefuseRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionLeaderMessage.UnionApplyAllRefuseRequest request) {
		String playerCode = messageSource.getTag();

		UnionLeaderMessage.UnionApplyAllRefuseResponse.Builder response = UnionLeaderMessage.UnionApplyAllRefuseResponse.newBuilder();

		// 管理员权限
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnionManager(entry);
		if (!result.equals(Result.UnionManager)) {
			send(messageSource, response, result);
			return;
		}
		RedisLock uLock = UnionBean.lock(entry.getUnionBean().getCode());
		try {
			if (uLock.tryLock()) {
				UnionBean union = entry.reloadUnionBean();

				union.getApplyList().clear();
				union.set();

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			uLock.unlock();
		}
	}

	private void send(MessageSource messageSource, UnionLeaderMessage.UnionApplyAllRefuseResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}